import torch.nn as nn
import torch.nn.functional as F

image_size=28
num_classes=10


depth = [4, 8]


class ConvNet(nn.Module):
    def __init__(self):
        super(ConvNet, self).__init__()

        self.conv1 = nn.Conv2d(1, depth[0], 5, 1, padding=2)
        self.pool = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(depth[0], depth[1], 5,1, padding=2)
        #pool
        self.fc1 = nn.Linear(image_size // 4 * image_size // 4 * depth[1], 512)
        self.fc2 = nn.Linear(512, num_classes)

    def forward(self, x):
        x = self.conv1(x)#28*28
        x = F.relu(x)

        x = self.pool(x)#14x14

        x = self.conv2(x)#14x14
        x = F.relu(x)
        x = self.pool(x)#7x7

        x = x.view(-1, image_size // 4 * image_size // 4 * depth[1])#7x7x8
        x = self.fc1(x)#512
        x = F.relu(x)

        x = F.dropout(x, training=self.training)
        x = self.fc2(x)

        x = F.log_softmax(x, dim=1)#softmax
        return x

    def retrieve_features(self, x):
        #提取两次卷积网络后的特征图
        map1 = F.relu(self.conv1(x))
        x = self.pool(map1)
        map2 = F.relu(self.conv2(x))
        return (map1, map2)


